package com.will.client.adapter;


import com.will.client.CustomChannelInitializer;
import com.will.entity.MethodInvokeMeta;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author 杨明智
 * @version:1.0
 * @create 2019年01月10日 4:31 PM
 * @description
 **/
public class ClientChannelHandlerAdapter extends ChannelInboundHandlerAdapter {

    private Logger logger = LoggerFactory.getLogger(ClientChannelHandlerAdapter.class);
    private MethodInvokeMeta methodInvokeMeta;
    private CustomChannelInitializer channelInitializerClient;

    public ClientChannelHandlerAdapter(MethodInvokeMeta methodInvokeMeta, CustomChannelInitializer channelInitializerClient) {
        this.methodInvokeMeta = methodInvokeMeta;
        this.channelInitializerClient = channelInitializerClient;
    }

    /**
     * 出现异常时
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.info("客户端出异常了,异常信息:{}", cause.getMessage());
        cause.printStackTrace();
        ctx.close();

    }

    /**
     * 通道活跃时
     * @param ctx
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        if (methodInvokeMeta.getMethodName().endsWith("toString")
                && !"class java.lang.String".equals(methodInvokeMeta.getReturnType().toString())) {
            logger.info("客户端发送信息参数:{},信息返回值类型：{}", methodInvokeMeta.getArgs(), methodInvokeMeta.getReturnType());
        }
        ctx.writeAndFlush(methodInvokeMeta);

    }

    /**
     * 有消息返回时
     * @param ctx
     * @param msg
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {

        channelInitializerClient.setResponse(msg);
    }

}
